<template>
  <div>
    <!-- ADD dialog start -->
    <el-dialog
        v-model="addVisible"
        title="添加任务"
        width="30%"
        align-center
    >
      <div>
        <el-form :model="addData" status-icon ref="addRef" label-width="80px" class="demo-ruleForm">
          <el-form-item label="名称" prop="taskName">
            <el-input v-model="addData.taskName"></el-input>
          </el-form-item>

          <el-form-item>
            <!-- exSript select start -->
            <el-select v-model="exScriptsValue" placeholder="后脚本选择">
              <el-option
                  v-for="item in exScripts"
                  :key="item.scriptName"
                  :label="item.scriptName"
                  :value="item.scriptId"
              >
                <span style="float: left">{{ item.scriptName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                  {{ item.scriptId }}
                </span>
              </el-option>
            </el-select>
            <!-- exSript select end -->
          </el-form-item>

          <el-form-item>
            <!-- backSript select start -->
            <el-select v-model="backScriptsValue" placeholder="前脚本选择">
              <el-option
                  v-for="item in backScripts"
                  :key="item.scriptName"
                  :label="item.scriptName"
                  :value="item.scriptId"
              >
                <span style="float: left">{{ item.scriptName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                  {{ item.scriptId }}
                </span>
              </el-option>
            </el-select>
            <!-- backSript select end -->
          </el-form-item>

          <el-form-item>
            <!-- imgset select start -->
            <el-select v-model="imgsetValue" placeholder="数据集选择">
              <el-option
                  v-for="item in imgset"
                  :key="item.imgsetName"
                  :label="item.imgsetName"
                  :value="item.imgsetId"
              >
                <span style="float: left">{{ item.imgsetName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
          {{ item.imgsetId }}
        </span>
              </el-option>
            </el-select>
            <!-- imgset select end -->
          </el-form-item>

          <el-form-item>
            <!-- model select start -->
            <el-select v-model="modelsValue" placeholder="模型选择">
              <el-option
                  v-for="item in models"
                  :key="item.modelId"
                  :label="item.modelName"
                  :value="item.modelId"
              >
                <span style="float: left">{{ item.modelName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
          {{ item.modelId }}
        </span>
              </el-option>
            </el-select>
            <!-- model select end -->
          </el-form-item>

          <el-form-item style="margin: 20px auto auto;">
            <el-button type="primary" @click="addSubmitForms">提交</el-button>
            <el-button @click="resetForm('signUp')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- ADD dialog end -->

    <!-- Modify dialog start -->
    <el-dialog
        v-model="modifyVisible"
        title="修改数据集"
        width="30%"
        align-center
    >
      <div>
        <el-form :model="modifyData" status-icon ref="modifyRef" label-width="80px" class="demo-ruleForm">
          <el-form-item label="名称" prop="taskName">
            <el-input v-model="modifyData.taskName"></el-input>
          </el-form-item>

          <el-form-item>
            <!-- exSript select start -->
            <el-select v-model="exScriptsValue" placeholder="Select">
              <el-option
                  v-for="item in exScripts"
                  :key="item.scriptName"
                  :label="item.scriptName"
                  :value="item.scriptId"
              >
                <span style="float: left">{{ item.scriptName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
          {{ item.scriptId }}
        </span>
              </el-option>
            </el-select>
            <!-- exSript select end -->
          </el-form-item>

          <el-form-item>
            <!-- backSript select start -->
            <el-select v-model="backScriptsValue" placeholder="Select">
              <el-option
                  v-for="item in backScripts"
                  :key="item.scriptName"
                  :label="item.scriptName"
                  :value="item.scriptId"
              >
                <span style="float: left">{{ item.scriptName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
          {{ item.scriptId }}
        </span>
              </el-option>
            </el-select>
            <!-- backSript select end -->
          </el-form-item>

          <el-form-item>
            <!-- imgset select start -->
            <el-select v-model="imgsetValue" placeholder="Select">
              <el-option
                  v-for="item in imgset"
                  :key="item.imgsetName"
                  :label="item.imgsetName"
                  :value="item.imgsetId"
              >
                <span style="float: left">{{ item.imgsetName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
          {{ item.imgsetId }}
        </span>
              </el-option>
            </el-select>
            <!-- imgset select end -->
          </el-form-item>

          <el-form-item>
            <!-- model select start -->
            <el-select v-model="modelsValue" placeholder="Select">
              <el-option
                  v-for="item in models"
                  :key="item.modelId"
                  :label="item.modelName"
                  :value="item.modelId"
              >
                <span style="float: left">{{ item.modelName }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
          {{ item.modelId }}
        </span>
              </el-option>
            </el-select>
            <!-- model select end -->
          </el-form-item>

          <el-form-item style="margin: 20px auto auto;">
            <el-button type="primary" @click="modifySubmitForms">提交</el-button>
            <el-button @click="resetForm('signUp')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- Modify dialog end -->

    <!-- check dialog start -->
    <el-dialog
        v-model="checkVisible"
        title="修改数据集"
        width="30%"
        align-center
    >
      <div>
        <el-form :model="checkData" status-icon ref="modifyRef" label-width="125px" class="demo-ruleForm">
          <el-form-item label="创建用户" prop="userId">
            <el-input v-model="checkData.userId" disabled></el-input>
          </el-form-item>
          <el-form-item label="使用的模型" prop="modelId">
            <el-input v-model="checkData.modelId" disabled></el-input>
          </el-form-item>
          <el-form-item label="使用的前处理脚本" prop="exScriptId">
            <el-input v-model="checkData.exScriptId" disabled></el-input>
          </el-form-item>
          <el-form-item label="使用的后处理脚本" prop="backScriptId">
            <el-input v-model="checkData.backScriptId" disabled></el-input>
          </el-form-item>
          <el-form-item label="最后一次运行时间" prop="lastRunTime">
            <el-input v-model="checkData.lastRunTime" disabled></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- check dialog end -->

    <!-- list_data start -->
    <div class="list_data_box">

      <div class="line"></div>
      <div class="gui_box">
        <el-input
            v-model="input3"
            placeholder="Please input"
            class="input-with-select"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
        <el-button @click="addView"  type="primary" style="margin-left: 380px;">创建任务</el-button>
        <el-button type="danger" :icon="Delete" @click="removeView"/>
      </div>


<!--      </el-table>-->
      <div v-for="(item,index) in displayedData" class="data_box">
        <!--        <span style="font-size:20px;margin-left:20px">{{ item.imgsetId }}</span>-->
        <div style="margin-left: 10px;color:black">数据集ID：{{ item.taskId }}</div>
        <div style="height:40px">
          <span style="font-size:20px;margin-left:20px;display:block;float:left;margin-top: 10px;color:black">{{ item.taskName }}</span>
          <span style="margin-left:40px;color:#8c8ca3;display:block;float:left;width:85px;margin-top: 10px;">{{ item.createTime }}</span>
        </div>
        <div style="color:#8c8ca3;margin-left:20px;margin-top:10px"><span>所属数据集: {{ item.imgsetId }}</span></div>
        <div style="float: right;margin-top: -45px;margin-right: 61px;">
          <el-button  @click="runTask(index)" style="margin-top:10px;margin-left:20px;border: none;">运行</el-button>
          <el-button :icon="Search" @click="checkView(index)" style="margin-top:10px;margin-left:20px;border: none;background-color: transparent">查看</el-button>
          <el-button :icon="EditPen" @click="modifyView(index)" style="margin-top:10px;border: none;background-color: transparent">修改</el-button>
          <el-button :icon="Delete" @click="removeView(index)" style="margin-top:10px;border: none;background-color: transparent">删除</el-button>
        </div>
      </div>
    </div>
    <!-- list_data end -->

    <div class="demo-pagination-block" style="margin-left: 30px; margin-top: 15px;">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import {onMounted, reactive, ref} from "vue";
import task from "@/api/task"
import {ElMessage, ElMessageBox} from "element-plus";
import imgs from "@/api/imgs";
import datasets from "@/api/datasets";
import {Delete, EditPen, Refresh, Search} from "@element-plus/icons-vue";
import quota from "@/api/quota";
import inference from "@/api/inference";

export default {
  name: "Task",
  setup() {
    // 选择模型
    const exScriptsValue = ref('')
    let exScripts = ref([])
    const backScriptsValue = ref('')
    let backScripts = ref([])
    const imgsetValue = ref('')
    let imgset = ref([])
    const modelsValue = ref('')
    let models = ref([])

    // 增加所用的数据模型
    const addData = ref({
      taskName:'',
    })
    const addRef = ref(null)
    const addVisible = ref(false)

    // 渲染数据模型
    let listData = reactive([])
    const selectedKeys = reactive([])
    let displayedData = reactive([])

    // 分页控制
    const currentPage = ref(1);
    const pageSize = ref(5);

    // 选择数据模型
    const taskIds = []

    // form修改数据模型
    const modifyData = ref({})
    const modifyRef = ref(null)
    let modifyId = 0
    const modifyVisible = ref(false)

    const checkVisible = ref(false)
    const checkData = ref({})

    // 初始化
    onMounted(()=>{
      getList()
    })

    // 查
    function getList(){
      let userId = JSON.parse(localStorage.getItem('userData')).userId
      let da = {}
      da.userId = userId
      exScripts.value.length = 0
      backScripts.value.length = 0

      task.list(da).then(res => {
        console.log(res)
        if(res.code == 200) {
          listData.length = 0
          listData.splice(0, res.data.length, ...res.data)
          listData.forEach(function(element){
            element.createTime = element.createTime.replace('T',' ')
            element.lastRunTime = element.lastRunTime.replace('T',' ')
          })
          currentPage.value = 1
          pageSize.value = 5
          const start = (currentPage.value - 1) * pageSize.value
          const end = start + pageSize.value
          displayedData.length = 0
          displayedData.splice(start, end, ...listData.slice(start, end))

          task.about(da).then(res =>{
            res.data.scripts.forEach(function (element){
              if(element.tag === 0){
                exScripts.value.push(element)
                console.log(exScripts)
              }else{
                backScripts.value.push(element)
              }
            })
            imgset.value = res.data.imgset
            models.value = res.data.models
          })
        }else{
          console.log(res)
        }
      })
    }

    // 增
    const addSubmitForms = () => {
      addRef.value.validate((valid) => {
        if(valid){
          let da = {}
          da.taskName = addData.value.taskName;
          const userId = JSON.parse(localStorage.getItem('userData')).userId.toString()
          da.userId = userId;
          da.exScriptId = exScriptsValue.value
          da.backScriptId = backScriptsValue.value
          da.imgsetId = imgsetValue.value
          da.modelId = modelsValue.value

          task.make(da).then(res =>{
            console.log(res)
            if(res.code == 200){
              console.log(res)
              ElMessage.success("增加成功")
              getList()
            }else{
              ElMessage.error("error！")
            }
          })
        }else{
          ElMessage.error("error！")
          return false
        }
      })
    }

    // 增加的弹出层
    function addView(){
      addVisible.value = true
    }

    //

    // 改
    const modifyView = (index) => {

      modifyVisible.value = true
      // modifyData.value.imgName = row.imgName
      modifyId = displayedData[index].taskId
      modifyData.value.taskName = displayedData[index].taskName
      imgsetValue.value = displayedData[index].imgsetId
      exScriptsValue.value = displayedData[index].exScriptId
      backScriptsValue.value = displayedData[index].backScriptId
      modelsValue.value = displayedData[index].modelId
    };

    // 改
    const checkView = (index) => {
      checkVisible.value = true
      // modifyData.value.imgName = row.imgName
      checkData.value.userId = displayedData[index].userId
      checkData.value.modelId = displayedData[index].modelId
      checkData.value.exScriptId = displayedData[index].exScriptId
      checkData.value.backScriptId = displayedData[index].backScriptId
      checkData.value.lastRunTime = displayedData[index].lastRunTime
    };

    // 改 提交
    const modifySubmitForms = () => {
      modifyRef.value.validate((valid) => {
        if(valid){
          let da = {}
          console.log(modifyId)
          da.taskId = modifyId
          da.taskName = modifyData.value.taskName;
          const userId = JSON.parse(localStorage.getItem('userData')).userId.toString()
          da.userId = userId;
          da.exScriptId = exScriptsValue.value
          da.backScriptId = backScriptsValue.value
          da.imgsetId = imgsetValue.value
          da.modelId = modelsValue.value

          console.log(da)
          task.modify(da).then(res =>{
            console.log(res)
            if(res.code == 200){
              console.log(res)
              ElMessage.success("修改成功")
              getList()
            }else{
              ElMessage.error("error！")
            }
          })
        }else{
          ElMessage.error("error！")
          return false
        }
      })
    }

    // 选择文件
    const handleSelectionChange = (selection) => {
      if(taskIds.length !== 0){
        taskIds.splice(0,taskIds.length)
      }
      selection.forEach((item) =>{
        taskIds.push(item.taskId)
      })
    }

    // 删
    function removeView(){
      if(taskIds.length === 0){
        ElMessageBox.alert('请勾选想要删除的数据！','Warning',{
          confirmButtonText:"OK"
        })
      }else{
        ElMessageBox.confirm(
            '您确定想要删除选中的数据集吗？',
            'Warning',
            {
              confirmButtonText:'OK',
              cancelButtonText:'Cancel',
              type: 'warning'
            }
        ).then(() => {
          task.remove(taskIds).then(res => {
            if(res.code == 200){
              ElMessage.success("删除成功")
              getList()
              taskIds.splice(0,taskIds.length)
            }
          })
        }).catch(() => {
          ElMessage({
            type:'info',
            message:"取消删除"
          })
        })
      }
    }

    const runTask = (index) => {
      console.log("运行任务",listData[index].taskId)

      let da = {}
      da.userId = JSON.parse(localStorage.getItem('userData')).userId
      quota.list(da).then(res => {
        if (res.code === 200) {
          console.log(res)
          if (res.data[0].quotaNum > 0) {
            console.log("开始推理")
            let ta = {}
            ta.taskId = listData[index].taskId
            inference.runTask(ta).then(res => {
              console.log(res)
              if (res.code === 200) {
                ElMessage.success("运行成功,请等待结果")
              } else {
                ElMessage.error("推理失败！")
              }
            })
          }
        } else {
          ElMessage.error("请求失败！")
        }
      })
    }

    // 下一页或上一页
    const handleCurrentChange = (newPage) => {
      console.log('Current page:', newPage);
      currentPage.value = newPage;
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      displayedData.length = 0
      displayedData.splice(start, end, ...listData.slice(start, end))
    };
    const handleSizeChange = (newSize) => {
      console.log('Current page:', newSize);
      pageSize.value = newSize;

      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      displayedData.length = 0
      displayedData.splice(start, end, ...listData.slice(start, end))
    }

    return{
      exScriptsValue,
      exScripts,
      addView,
      backScripts,
      backScriptsValue,
      imgsetValue,
      imgset,
      modelsValue,
      models,
      addVisible,
      addData,
      addRef,
      addSubmitForms,
      listData,
      selectedKeys,
      taskIds,
      getList,
      modifyData,
      modifyRef,
      modifyVisible,
      modifyView,
      modifySubmitForms,
      handleSelectionChange,
      removeView,
      Delete,
      Search,
      Refresh,
      currentPage,
      pageSize,
      displayedData,
      handleSizeChange,
      handleCurrentChange,
      EditPen,
      checkVisible,
      checkView,
      checkData,
      runTask
    }
  }
}
</script>

<style scoped>
.list_data_box{
  width:100%;
  height: 88vh;
  padding:0;
  margin-top: 22px;
}
.el-table{
  width: 82% !important;
  height: 89%
}
.gui_box{
  background-color: rgb(255 255 255 / 60%);
  border-bottom: 2px solid #d9d9d9;
  width: 87.7%;
  height: 55px;
  margin-left:15px
}
.el-input-group{
  width: 30%;
  left: 10px;
}
.line{
  height: 25px;
  width: 87.7%;;
  background-color: rgb(255 255 255 / 60%);
  margin-left:15px;
  border-radius: 10px 10px 0 0;
}
/*.demo-pagination-block{*/
/*  width:82%*/
/*}*/
.data_box{
  width: 87.7%;
  text-align: initial;
  height: 115px;
  background-color: rgb(255 255 255 / 60%);
  /*border: 1px solid*/
  color: #8c8ca3;
  margin-left:15px
}
</style>